package org.pb.pet.service.impl;

import org.pb.basic.service.impl.BaseServiceImpl;
import org.pb.basic.utils.*;
import org.pb.order.domain.PetAcquisitionOrder;
import org.pb.order.mapper.PetAcquisitionOrderMapper;
import org.pb.order.service.IPetAcquisitionOrderService;
import org.pb.org.domain.Employee;
import org.pb.org.domain.Shop;
import org.pb.org.mapper.EmployeeMapper;
import org.pb.org.mapper.ShopMapper;
import org.pb.pet.domain.Pet;
import org.pb.pet.domain.SearchMasterMsg;
import org.pb.pet.mapper.SearchMasterMsgMapper;
import org.pb.pet.query.SearchMasterMsgQuery;
import org.pb.pet.service.IPetService;
import org.pb.pet.service.ISearchMasterMsgService;
import org.pb.user.domain.LoginInfo;
import org.pb.user.mapper.LoginInfoMapper;
import org.pb.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 寻主信息的业务实现类
 * @author pb
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg, SearchMasterMsgQuery> implements ISearchMasterMsgService {
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private LoginInfoMapper loginInfoMapper;

    @Autowired
    private IPetService petService;

    @Autowired
    private IPetAcquisitionOrderService petAcquisitionOrderService;

    @Override
    public List<SearchMasterMsg> getAll() {
        return searchMasterMsgMapper.findAll();
    }

    @Override
    @Transactional
    public AjaxResult publish(SearchMasterMsg msg, HttpServletRequest request) {
        // 对寻主信息进行非空判断
        if (msg.getTitle().isEmpty() || msg.getAddress().isEmpty()) {
            throw new RuntimeException("标题和地址不能为空，请正确填写信息");
        }
        // 通过工具类，获取到对应的用户登陆信息
        LoginInfo loginInfo = LoginContextUtils.getLoginInfo(request);
        // 通过loginInfo的id值，获取到对应的user_id
        Long user_id =  userMapper.getByLoginInfo(loginInfo);
        // 如果user_id为空的话，表示找不到对应的用户的数据
        if (user_id == null) {
            throw new RuntimeException("找不到您的用户信息，请先注册或登陆");
        }
        // 获取到当前的所有店铺信息，并通过地址获取到最近的店铺，进行寻主信息发布
        List<Shop> shops = shopMapper.findAll();
        // 如果没有获取到店铺信息，表示当前没有店铺营业
        if (shops == null || shops.size() <= 0) {
            throw new RuntimeException("当前没有店铺在营业，请稍后发布信息");
        }
        // 调用DistanceUtil工具类，获取到当前距离最近的宠物店
        Shop shop = DistanceUtil.getNearestShop(DistanceUtil.getPoint(msg.getAddress()), shops);
        // 将对应的shop_id、user_id添加到msg中
        msg.setShop_id(shop.getId());
        msg.setUser_id(user_id);
        // 将该信息添加到寻主信息表中
        searchMasterMsgMapper.save(msg);
        // 获取到店铺管理员的联系方式
        Employee emp = employeeMapper.loadById(shop.getAdmin_id());
        // 给对应店铺发送消息
//        SmsUtil.sendMsg(emp.getPhone(), "您有订单达到，请尽快到【" + msg.getAddress() + "】处理");
        System.out.println("您有订单达到，请尽快处理哦");
        // 如果有price值，需要创建订单 @TODO 同步信息到pet表中
        return AjaxResult.successWithMessage("寻主消息发布成功");
    }

    @Override
    public PageList<SearchMasterMsg> pendingQuery(SearchMasterMsgQuery query, HttpServletRequest request) {
        return getPageQuery(query, request, 0);
    }

    @Override
    public PageList<SearchMasterMsg> processedQuery(SearchMasterMsgQuery query, HttpServletRequest request) {
        return getPageQuery(query, request, 1);
    }

    /**
     * 抽取的获取对应寻主信息的方法
     * @param query
     * @param request
     * @param state
     * @return
     */
    public PageList<SearchMasterMsg> getPageQuery(SearchMasterMsgQuery query, HttpServletRequest request, Integer state) {
        // 获取到当前登陆用户的信息
        LoginInfo loginInfo = LoginContextUtils.getLoginInfo(request);
        // 通过loginInfoId获取到对应的管理员信息，进而获取到对应的shopId
        Employee emp = employeeMapper.getByLogInfoId(loginInfo);
        query.setShopId(emp.getShop_id());
        // 将查询的寻主信息状态设置为对应的状态
        query.setState(state);
        // 执行分页查询
        List<SearchMasterMsg> msgs = searchMasterMsgMapper.findByQuery(query);
        // 得到记录总条数
        Integer totals = searchMasterMsgMapper.countQuery(query);
        // 将结果封装到pageList工具类对象中
        PageList<SearchMasterMsg> pageList = new PageList<>();
        pageList.setTotals(totals);
        pageList.setData(msgs);
        return pageList;
    }

    @Override
    public PageList<SearchMasterMsg> userQuery(SearchMasterMsgQuery query, HttpServletRequest request) {
        return null;
    }

    @Override
    @Transactional
    public void handle(Pet pet, HttpServletRequest request) {
        System.err.println(pet);
        /*
         * 宠物处理流程：
         *  1. 首先要将寻主信息的状态修改1 —— state = 1;即表示该寻主信息已处理。 修改条件为当前寻主信息id
         *  2. 保存对应的宠物信息：
         *      1. 如果寻主信息中有成本价格，即原宠物主售卖宠物给店铺，则需要生成订单【收购订单、立即交易没有最迟确认时间】
         *          1. 将支付状态修改为已完成。
         *          2. 设置订单的支付方式。
         *          3. 添加订单的支付价格、宠物id、店铺id、收宠地址、用户id、店铺管理员id
         *          4. 通过工具类生成一个支付的唯一标识，生成一个订单的唯一标识
         *          5. 创建当前订单的摘要
         *      2. 如果寻主信息中没有成本价格，就表示宠物主是免费寄售宠物，不用创建订单，直接完成交易。
         */
        // 1. 先将对应的寻主信息的状态修改为已处理 state=1， 修改的id为search_master_msg_id
        searchMasterMsgMapper.updateById(pet.getSearch_master_msg_id());
        // 2.0 修改了寻主信息状态之后，修改对饮的宠物信息和宠物明细信息
        petService.save(pet, request);
        // 2.1 判断宠物信息中是否有成本价
        if (pet.getCostprice() != null) {
            System.err.println(pet.getSearch_master_msg_id());
            System.err.println(searchMasterMsgMapper.loadById(pet.getSearch_master_msg_id()));
            // 将宠物中的信息转化为宠物收购订单对象
            PetAcquisitionOrder petAcquisitionOrder = pet2order(pet, searchMasterMsgMapper.loadById(pet.getSearch_master_msg_id()), request);
            // 中间是否还有支付过程？？ 待定@TODO
            // 将该订单信息保存到数据库中
            petAcquisitionOrderService.save(petAcquisitionOrder);
        }
    }

    private PetAcquisitionOrder pet2order(Pet pet, SearchMasterMsg adopt, HttpServletRequest request) {
        PetAcquisitionOrder order = new PetAcquisitionOrder();
        order.setDigest("[摘要]对"+pet.getName()+"收购订单！");
        order.setState(0);//待支付
        order.setPrice(pet.getCostprice());
        order.setAddress(adopt.getAddress());
        String orderSn = CodeGenerateUtils.generateOrderSn(adopt.getUser_id());
        order.setOrderSn(orderSn);
        order.setPet_id(pet.getId());
        order.setUser_id(adopt.getUser_id());
        order.setPaytype(0);
        order.setShop_id(pet.getShop_id());
        order.setEmp_id(employeeMapper.getByLogInfoId(LoginContextUtils.getLoginInfo(request)).getId());
        return order;
    }

}
